<template>
    <div>
        <div class="page-comon-header">
            <div class="left">
                <label class="font14 margin-r-5">筛选</label>
                <el-select
                    v-model="search.category"
                    clearable
                    @change="handleCategoryChange"
                    placeholder="请选择类别">
                    <el-option
                        v-for="item in categories"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                </el-select>
                <el-select
                    v-model="search.supplierId"
                    clearable
                    @change="handleSupplierChange"
                    placeholder="请选择供应商"
                    style="margin-left: 10px;">
                    <el-option
                        v-for="item in suppliers"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                </el-select>
            </div>
            <div class="right">
                <div class="right-item text-center">
                    <span class="font28 padding-b-10">{{totalProducts}}</span>
                    <p class="font14 txt-info">产品数量</p>
                </div>
            </div>
        </div>
        
        <div class="page-search-bar">
            <div class="left">
                <label class="font14 margin-r-5">搜索产品</label>
                <el-input
                    placeholder="输入关键词"
                    icon="search"
                    v-model="search.keyword"
                    @change="handleKeywordChange"
                    :on-icon-click="handleIconClick">
                </el-input>
            </div>
            <div class="right">
                <el-badge :value="0" :max="99" class="margin-r-15">
                    <el-button
                        disabled
                        :plain="true"
                        type="danger"
                        @click="handleBatchDelete">批量删除</el-button>
                </el-badge>
                <router-link to="/product/add">
                    <el-button
                        class="margin-l-15"
                        type="primary">添加产品</el-button>
                </router-link>
                
            </div>
        </div>
        
        <el-table
            row-class-name="rowStyle"
            :data="tableData" 
            stripe 
            style="width: 100%"
            @selection-change="handleSelectionChange">
            <el-table-column
                type="selection"
                align="center"
                width="55">
            </el-table-column>
            <el-table-column
                prop="name"
                label="产品名称">
            </el-table-column>
            <el-table-column
                prop="category"
                label="类别"
                width="100">
                <template scope="scope">
                    <el-tag
                        :type="scope.row.category === '速冻类' ? 'primary' : 
                              scope.row.category === '半成品类' ? 'success' : 
                              scope.row.category === '即食类' ? 'warning' : 'info'">
                        {{scope.row.category}}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column
                prop="supplier"
                label="供应商">
            </el-table-column>
            <el-table-column
                prop="price"
                label="价格"
                width="100">
                <template scope="scope">
                    ¥ {{scope.row.price}}
                </template>
            </el-table-column>
            <el-table-column
                prop="temp"
                label="温度要求"
                width="120">
                <template scope="scope">
                    {{scope.row.tempMin}}°C ~ {{scope.row.tempMax}}°C
                </template>
            </el-table-column>
            <el-table-column
                prop="shelfLife"
                label="保质期"
                width="80">
                <template scope="scope">
                    {{scope.row.shelfLife}}天
                </template>
            </el-table-column>
            <el-table-column
                prop="status"
                label="状态"
                width="80">
                <template scope="scope">
                    <el-tag
                        :type="scope.row.status === '正常' ? 'success' : 'danger'">
                        {{scope.row.status}}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column
                prop="action"
                label="操作"
                width="220">
                <template scope="scope">
                    <el-button 
                        size="small"
                        :plain="true"
                        @click="handleDetail(scope.$index, scope.row)">详情</el-button>
                    <el-button
                        size="small"
                        :plain="true"
                        type="primary"
                        style="margin-left: 0;" 
                        @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button
                        size="small"
                        :plain="true"
                        type="danger"
                        style="margin-left: 0;"
                        @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination-bar margin-t-15" v-show="pagination.total > 10">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="pagination.currentPage"
            :page-size="pagination.pageSize"
            layout="total, prev, pager, next"
            :total="pagination.total">
          </el-pagination>
        </div>
    </div>
</template>

<script>
import axios from 'axios';
export default {
    data() {
        return {
            // 搜索字段
            search: {
                category: '',
                supplierId: '',
                keyword: '',
                page: 1,
            },
            
            // 是否加载中
            loading: false,
            
            // 选择的行
            selectedRows: [],
            
            // 产品类别
            categories: [
                { value: '', label: '全部类别' },
                { value: '速冻类', label: '速冻类' },
                { value: '半成品类', label: '半成品类' },
                { value: '即食类', label: '即食类' }
            ],
            
            // 供应商列表
            suppliers: [
                { value: '', label: '全部供应商' },
                { value: '1', label: '湖南农耕食品有限公司' },
                { value: '2', label: '四川味宝食品科技有限公司' }
            ],
            
            // 表格数据
            tableData: [],
            
            // 分页器数据
            pagination: {
                currentPage: 1,
                pageSize: 10,
                total: 0,
            },

            // 产品总数
            totalProducts: 0
        }
    },
    
    created() {
        this.getProductList();
        this.getSuppliersList();
    },
    
    methods: {
        // 获取产品列表
        getProductList() {
            this.loading = true;
            
            // 实际API调用
            axios.get('/api/products', {
                params: this.search
            }).then(response => {
                if (response.data.status === 'success') {
                    this.tableData = response.data.items;
                    this.pagination.total = response.data.total;
                    this.totalProducts = response.data.total;
                } else {
                    this.$message.error(response.data.message || '获取产品列表失败');
                }
            }).catch(err => {
                console.error('获取产品列表失败:', err);
                this.$message.error('获取产品列表失败');
            }).finally(() => {
                this.loading = false;
            });
        },
        
        // 获取供应商列表
        getSuppliersList() {
            // 实际API调用
            axios.get('/api/suppliers').then(response => {
                if (response.data.status === 'success') {
                    this.suppliers = [
                        { value: '', label: '全部供应商' },
                        ...response.data.items.map(item => ({
                            value: item.id.toString(),
                            label: item.name
                        }))
                    ];
                } else {
                    this.$message.error(response.data.message || '获取供应商列表失败');
                }
            }).catch(err => {
                console.error('获取供应商列表失败:', err);
                this.$message.error('获取供应商列表失败');
            });
        },
        
        handleCategoryChange(value) {
            this.search.category = value;
            this.getProductList();
        },
        
        handleSupplierChange(value) {
            this.search.supplierId = value;
            this.getProductList();
        },
        
        handleCurrentChange(page) {
            this.pagination.currentPage = page;
            this.search.page = page;
            this.getProductList();
        },
        
        handleDelete(index, row) {
            this.$confirm('确认删除该产品?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 实际调用
                axios.delete('/api/products/' + row.id).then(response => {
                    if (response.data.status === 'success') {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.getProductList();
                    } else {
                        this.$message.error(response.data.message || '删除失败');
                    }
                }).catch(err => {
                    if (err.response && err.response.data && err.response.data.message) {
                        this.$message.error(err.response.data.message);
                    } else {
                        console.error('删除产品失败:', err);
                        this.$message.error('删除产品失败');
                    }
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
        },
        
        handleBatchDelete() {
            if (this.selectedRows.length === 0) {
                this.$message({
                    type: 'warning',
                    message: '请选择要删除的产品'
                });
                return;
            }
            
            this.$confirm(`确认删除选中的 ${this.selectedRows.length} 个产品?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 实际调用
                const ids = this.selectedRows.map(row => row.id);
                axios.post('/api/products/batch-delete', { ids }).then(response => {
                    if (response.data.status === 'success') {
                        this.$message({
                            type: 'success',
                            message: response.data.message || '批量删除成功!'
                        });
                        this.getProductList();
                    } else {
                        this.$message.error(response.data.message || '批量删除失败');
                    }
                }).catch(err => {
                    if (err.response && err.response.data && err.response.data.message) {
                        this.$message.error(err.response.data.message);
                        
                        // 如果存在关联关系，显示详细信息
                        if (err.response.data.products_with_relations) {
                            const products = err.response.data.products_with_relations;
                            let message = '以下产品无法删除（存在关联数据）：<br>';
                            products.forEach(p => {
                                message += `- ${p.name}: ${p.record_count}个关联记录<br>`;
                            });
                            this.$alert(message, '删除失败', {
                                dangerouslyUseHTMLString: true,
                                confirmButtonText: '确定'
                            });
                        }
                    } else {
                        console.error('批量删除产品失败:', err);
                        this.$message.error('批量删除产品失败');
                    }
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
        },
        
        handleSelectionChange(val) {
            this.selectedRows = val;
        },
        
        handleKeywordChange(value) {
            this.search.keyword = value;
        },
        
        handleIconClick(e) {
            this.getProductList();
        },
        
        handleDetail(index, row) {
            this.$router.push({
                path: '/product/detail',
                query: { id: row.id }
            });
        },
        
        handleEdit(index, row) {
            this.$router.push({
                path: '/product/edit',
                query: { id: row.id }
            });
        }
    }
}
</script>

<style scoped>
    .right-item {
        padding-right: 50px;
    }
    .pagination-bar {
        display: flex;
        justify-content: center;
    }
    .rowStyle {
        height: 50px;
    }
    
    .page-search-bar .left {
        display: flex;
        align-items: center;
    }
    .page-search-bar .left label {
        width: 80px;
    }
    
    .page-search-bar .right {
        display: flex;
        align-items: center;
    }
</style> 